package com.itheima.controller;

import com.itheima.EResultCode;
import com.itheima.MyBusinessException;
import com.itheima.entity.Result;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.concurrent.TimeoutException;

/**
 * @Author G_Y
 * @Date 2020/6/14 9:13
 * @Description: 统一异常捕获
 **/
@ControllerAdvice
public class ExcetpionHandlerControllerAdvice {
    static HashMap<Class<? extends Exception>, EResultCode> eMap =
            new HashMap<>();
    static {
        eMap.put(TimeoutException.class, EResultCode.TIMEOUT);
        // 把你觉得需要单独维护的异常-提示 维护到map
        //
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result handleException(Exception e) {
        Class<? extends Exception> aClass = e.getClass();
        EResultCode resultCode = null;
        if((resultCode = eMap.get(aClass)) == null) {
            return new Result(EResultCode.UNK_E);
        }
        return new Result(resultCode);
    }

    @ExceptionHandler(MyBusinessException.class)
    @ResponseBody
    public Result handleException(MyBusinessException e) {
        EResultCode resultCode = e.geteResultCode();
        return new Result(resultCode);
    }

}
